package com.k8.common.executor.threadPool;

import com.k8.rpc.url.URL;

import java.util.concurrent.*;

import static com.k8.common.constants.CommonConstants.*;
import static com.k8.common.constants.CommonKeyConstants.*;
import static com.k8.common.executor.NamedThreadFactory.USER_THREAD_FACTORY;

/**
 * dubbo中特殊的
 * <p>
 * 还有个eagerThreadPool
 * 当发生组设了就创建新线程不放到阻塞队列中
 */
public class LimitedThreadPool extends AbstractThreadPool {
    @Override
    protected ExecutorService doGetExecutor(URL url, int core, int max, int limit) {
        BlockingQueue<Runnable> blockingQueue = new SynchronousQueue<>();
        String reject = url.getParameter(REJECT_POLICY_KEY);
        if (reject != null) {
            if (DISCARD_REJECT.equals(reject)) {
                return new ThreadPoolExecutor(core, limit, Long.MAX_VALUE, TimeUnit.MILLISECONDS, blockingQueue, USER_THREAD_FACTORY, new ThreadPoolExecutor.DiscardPolicy());
            } else if (DISCARD_OLDEST_REJECT.equals(reject)) {
                return new ThreadPoolExecutor(core, limit, Long.MAX_VALUE, TimeUnit.MILLISECONDS, blockingQueue, USER_THREAD_FACTORY, new ThreadPoolExecutor.DiscardOldestPolicy());
            }
        }
        return new ThreadPoolExecutor(core, limit, Long.MAX_VALUE, TimeUnit.MILLISECONDS, blockingQueue, USER_THREAD_FACTORY);
    }
}
